import 'package:gold/app/user_provider.dart';
import 'package:gold/base/config.dart';
import 'package:gold/base/view_model.dart';
import 'package:gold/http/api_address.dart';
import 'package:gold/http/api_order.dart';
import 'package:gold/http/http.dart';
import 'package:gold/model/address_model.dart';
import 'package:gold/model/goods_detail_model.dart';
import 'package:gold/route/routes.dart';
import 'package:gold/route/xfg_nav.dart';
import 'package:gold/utils/xfg_extension.dart';
import 'package:gold/widgets/dialog/pickup_coupon_dialog.dart';
import 'package:gold/widgets/dialog/pickup_deduction_dialog.dart';

/// @description:
/// @author tangzhentao
/// @created at 20:02 2024/11/30


class GoodsOrderViewmodel extends Viewmodel {
  /// 商品信息
  final GoodsDetailModel goods;

  int _number = 1;
  /// 数量
  int get number => _number;
  set number(int value) {
    if (_number != value) {
      _number = value;
      _coupon = null;
      _pointNumber = 0;
      _balanceNumber = 0;
      _calMoney();
      notifyListeners();
    }
  }

  AddressModel? _address;
  /// 地址
  AddressModel? get address => _address;

  CouponPick? _coupon;
  /// 优惠券
  CouponPick? get coupon => _coupon;

  bool _showDeduction = false;
  /// 是否展示抵扣
  bool get showDeduction => _showDeduction;
  set showDeduction(bool value) {
    if (_showDeduction != value) {
      _showDeduction = value;
      notifyListeners();
    }
  }

  int _pointNumber = 0;
  /// 积分抵扣数量
  int get pointNumber =>_pointNumber;

  double _balanceNumber = 0;
  /// 余额抵扣数量
  double get balanceNumber =>_balanceNumber;

  double _payAmount = 0;
  /// 支付金额
  double get payAmount => _payAmount;

  double _deduction = 0;
  /// 抵扣总金额
  double get deduction => _deduction;

  GoodsOrderViewmodel(this.goods) {
    _updateAmount();
  }

  /// 更新用户剩余金额
  Future _updateAmount() async {
    final userProvider = XfgNav.read<UserProvider>();
    await userProvider.updateProfile();
    final user = userProvider.user;
    _showDeduction = (user.points?? 0) > 0 || (user.amount?? 0) > 0;
    final result = await Http().request<AddressModel>(ApiAddress.addressDefault, showErrorMsg: false);
    if (result.success && result.data!= null) _address = result.data;
    _calMoney();
  }

  /// 初始化计算金额
  void _calMoney() {
    double total = (goods.price?? 0) * number + (goods.freight?? 0);
    _deduction = 0;
    if (coupon != null && !coupon!.noCoupon) {
      final discountAmount = coupon!.coupon.discountAmount?? 0;
      total = total - discountAmount;
      _deduction += discountAmount;
    }
    if (total > 0) {
      total = total - _pointNumber - _balanceNumber;
      _deduction += (_pointNumber + _balanceNumber);
      _payAmount = total < 0 ? 0:total;
    } else {
      _showDeduction = false;
    }
    notifyListeners();
  }

  /// 选择地址
  Future pickAddress() async {
    final result = await XfgNav.pushNamed<AddressModel>(Routes.myAddress, arguments: true);
    if (result != null) {
      _address = result;
      notifyListeners();
    }
  }

  /// 选择优惠券
  Future pickupCoupon() async {
    final result = await showPickupCouponDialog(picked: _coupon, minAmount: (goods.price?? 0) * number);
    if (result != null) {
      _coupon = result;
      _calMoney();
    }
  }

  /// 选择抵扣
  Future pickupDeduction() async {
    double total = (goods.price?? 0) * number + (goods.freight?? 0);
    if (coupon != null && !coupon!.noCoupon) {
      final discountAmount = coupon!.coupon.discountAmount?? 0;
      total = total - discountAmount;
    }
    final user = XfgNav.read<UserProvider>().user;
    final result = await showPickupDeductionDialog(payingAmount: total, availablePoints: user.points?? 0, availableBalance: user.amount?? 0);
    if (result != null) {
      _pointNumber = result.pointNumber;
      _balanceNumber = result.balance;
      _calMoney();
    }
  }

  /// 立即支付
  Future payNow() async {
    if (_address == null) {
      '请先选择收货地址'.info();
     return;
    }
    final orderRequest = OrderRequest(_payAmount, _address?.id, goods.id, _number, pointNumber, _payAmount, _coupon?.coupon.userCouponId);
    final result = await Http().request<int>(ApiOrder.create, data: orderRequest.toJson(), loadingText: '创建订单...');
    if (result.success) {
      XfgNav.read<UserProvider>().updateProfile();
      if (result.data != null) {
        if (_payAmount > 0) {
          XfgNav.pushReplacementNamed(Routes.pay, arguments: {'type': ProductType.product, 'id': result.data!, 'amount': _payAmount});
        } else {
          XfgNav.pushReplacementNamed(Routes.paySuccess, arguments: {'type': ProductType.product, 'id': result.data!});
        }
      } else {
        '订单信息异常'.error();
      }
    }
  }
}